import {
  jiekoulogin,
  logout,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import router, {
  resetRouter,
  setRouter
} from '@/router'
import Layout from '@/layout'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    name: '', //角色名称,
    routerList: [] //菜单栏
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    localStorage.setItem("jiazhengid", JSON.stringify(token))
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  setUserRole(state, role) {
    state.userRole = role;
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      jiekoulogin({
        username: username.trim(),
        pwd: password.trim()
      }).then(response => {
        localStorage.setItem('userId', response.data.id)
        commit('setUserRole', response.data.Quanxian.name);
        commit('SET_TOKEN', response.data.id)
        const obj = JSON.parse(response.data.Quanxian.content)
        state.routerList = obj[0].children.filter(item => item.checked).map(item => {
          return {
            path: item.path,
            component: Layout,
            children: [{
              path: item.path.slice(1),
              name: item.path.slice(1),
              component: () => import(`@/views${item.path}/index`),
              meta: {
                title: item.title,
                icon: item.icon
              }
            }],
            ...item,
          }
        })
        setToken(111)
        localStorage.setItem('sidermenu', JSON.stringify(state.routerList))
        resolve()

      }).catch(error => {
        // console.log(error)
        reject(error)
      })
    })
  },
  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {
          data
        } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const {
          name,
          avatar
        } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      removeToken() // must remove  token  first
      resetRouter()
      localStorage.removeItem("jiazhengid")
      commit('RESET_STATE')
      resolve()
      // }).catch(error => {
      // 	reject(error)
      // })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
